package java8.stream.demo07reducestream;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

import java.util.Arrays;
import java.util.Optional;
import java.util.stream.Stream;

/**
 * @author ChangLiang
 * @date 2020/4/22
 */
public class AppTest {

    Stream<Integer> stream;

    @BeforeEach
    public void setUp(){
        stream = Arrays.stream(new Integer[]{1, 2, 3, 4, 5, 6, 7});
    }

    @Test
    @DisplayName("test stream reduce")
    public void test(){
        Integer result = stream.reduce(0, (a, b) -> a + b);
        System.out.println(result);
    }

    @Test
    @DisplayName("test stream reduce")
    public void test2() {
        stream.reduce(Integer::sum).ifPresent(System.out::println);
    }

    @Test
    @DisplayName("test stream max")
    public void test3() {
        stream.reduce(Integer::max).ifPresent(System.out::println);
    }

    @Test
    @DisplayName("test stream min")
    public void test4(){
        stream.reduce(Integer::min).ifPresent(System.out::println);
    }

    @Test
    @DisplayName("test stream reduce")
    public void test5() {
        System.out.println(stream.filter(i -> i % 2 == 0).reduce(1, (a, b) -> a * b));
    }

    @Test
    @DisplayName("test stream reduce")
    public void test6() {
        stream = null;
        System.out.println(Optional.ofNullable(stream).orElse(Arrays.stream(new Integer[]{})).filter(i -> i % 2 == 0).reduce(0, (a, b) -> a + b));
    }

}
